﻿using LightCAD.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Weikio.PluginFramework.Abstractions;
using Weikio.PluginFramework.Catalogs;

namespace LightCAD.Runtime
{
    public static class PluginManager
    {
        public static List<Plugin> Plugins { get; internal set; }=new List<Plugin>();   
        public static List<ILcPlugin> PluginInstances { get; internal set; } = new List<ILcPlugin>();

        public static async Task LoadPlugins()
        {
            var pluginCfg = Path.Combine(AppContext.BaseDirectory, "plugins.json");
            if (File.Exists(pluginCfg))
            {
                try
                {
                    var cfg = JsonObject.Parse(File.ReadAllText(pluginCfg));
                }catch(Exception ex)
                {
                    LcLog.Write(LogType.Error, ex);
                }
            }

            var pluginFolder = Path.Combine(AppContext.BaseDirectory, "plugins");
            if (Directory.Exists(pluginFolder))
            {
                var folderPluginCatalog = new FolderPluginCatalog(pluginFolder, type =>
                {
                    type.Implements<ILcPlugin>();
                });
                await folderPluginCatalog.Initialize();
                Plugins.AddRange(folderPluginCatalog.GetPlugins());
            }

            foreach (var plugin in Plugins)
            {
                Console.WriteLine(plugin.Name);
                var instance = (ILcPlugin?)Activator.CreateInstance(plugin);
                if (instance != null)
                {
                    try
                    {
                        instance.Loaded();
                    }catch(Exception ex)
                    {
                        AppRuntime.UISystem.ShowException(ex);
                    }
                }
                PluginInstances.Add(instance);
            }
        }
    }
}
